<!--
  * 分包商表
  *
  * @Author:    ASDFH
  * @Date:      2024-07-30 17:14:53
  * @Copyright  sdfgh
-->
<template>
  <a-modal :title="form.id ? '编辑' : '添加'" width="300" :open="visibleFlag" @cancel="onClose" :maskClosable="false"
    :destroyOnClose="true" style="width: 900px;">
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 7 }">
      <a-row>
        <a-col :span="12">
          <a-form-item label="企业名称" name="companyName">
            <a-input style="width: 100%" v-model:value="form.companyName" placeholder="企业名称" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="社会统一信用代码" name="infoCode">
            <a-input style="width: 100%" v-model:value="form.infoCode" placeholder="社会统一信用代码" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="成立时间" name="foundingTime">
            <a-date-picker show-time valueFormat="YYYY-MM-DD HH:mm:ss" v-model:value="form.foundingTime"
              style="width: 100%" placeholder="成立时间" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="法人代表" name="legalRepresentative">
            <a-input style="width: 100%" v-model:value="form.legalRepresentative" placeholder="法人代表" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="企业性质" name="companyProperty">
            <a-select style="width: 100%" v-model:value="form.companyProperty" placeholder="企业性质">
              <a-select-option v-for="(item, index) in billType3" :key="index" :value="item.dictValueId">{{
                item.valueName }}</a-select-option>

            </a-select>
            <!-- <a-input style="width: 100%" v-model:value="form.companyProperty" placeholder="企业性质" /> -->
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="经营地址" name="businessAddress">
            <a-input style="width: 100%" v-model:value="form.businessAddress" placeholder="经营地址" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="联系电话" name="phone">
            <a-input style="width: 100%" v-model:value="form.phone" placeholder="联系电话" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="邮箱" name="email">
            <a-input style="width: 100%" v-model:value="form.email" placeholder="邮箱" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="联系地址" name="contactAddress">
            <a-input style="width: 100%" v-model:value="form.contactAddress" placeholder="联系地址" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="开户行" name="openingBank">
            <a-input style="width: 100%" v-model:value="form.openingBank" placeholder="开户行" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="收款账户" name="receiverAccount">
            <a-input style="width: 100%" v-model:value="form.receiverAccount" placeholder="收款账户" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="发票类别" name="invoiceType">
            <a-select style="width: 100%" v-model:value="form.invoiceType" placeholder="发票类别">
              <a-select-option v-for="(item, index) in billType" :key="index" :value="item.dictValueId">{{
                item.valueName }}</a-select-option>

            </a-select>
            <!-- <a-input style="width: 100%" v-model:value="form.invoiceType" placeholder="发票类别" /> -->
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="发票税率" name="invoiceTaxRate">
            <a-input style="width: 100%" v-model:value="form.invoiceTaxRate" placeholder="发票税率" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="结算方式" name="paymentPattern">
            <a-select style="width: 100%" v-model:value="form.paymentPattern" placeholder="结算方式">
              <a-select-option v-for="(item, index) in billType2" :key="index" :value="item.dictValueId">{{
                item.valueName }}</a-select-option>

            </a-select>
            <!-- <a-input style="width: 100%" v-model:value="form.paymentPattern" placeholder="结算方式" /> -->
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="营业执照" name="licenseUrl">
            <!-- <a-input style="width: 100%" v-model:value="form.licenseUrl" placeholder="营业执照" /> -->
            <a-upload name="file" list-type="picture-card" class="avatar-uploader" :show-upload-list="false"
              :multiple="false" :maxCount="1" :before-upload="beforeUpload" :action="uploadUrl"
              :customRequest="selfUpload" @change="handleChangeFile">
              <div v-if="form.licenseUrl">
                <viewer>
                  <img :src="form.licenseUrl" alt="avatar" shape="square" style="width: 120px;height: 120px;" />
                </viewer>
              </div>
              <div v-else>
                <a-icon type="plus" />
                <div class="ant-upload-text">上传执照</div>
              </div>
            </a-upload>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="备注" name="remark">
            <a-textarea style="width: 100%" v-model:value="form.remark" placeholder="备注" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <template #footer>
      <a-space v-if="form.type != 3">
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">保存</a-button>
      </a-space>
    </template>
  </a-modal>
</template>
<script setup>
import { reactive, ref, nextTick } from 'vue';
import _ from 'lodash';
import { message } from 'ant-design-vue';
import { SmartLoading } from '/@/components/framework/smart-loading';
import { subcontractorInfoApi } from '/@/api/business/subcontractor-info/subcontractor-info-api.js';
import { smartSentry } from '/@/lib/smart-sentry';
import { FILE_FOLDER_TYPE_ENUM } from '/@/constants/support/file-const';

const uploadModalFlag = ref(false)

// ------------------------ 事件 ------------------------

const emits = defineEmits(['reloadList']);

const beforeUpload = (file) => {
 
};
function selfUpload({ action, file, onSuccess, onError, onProgress }) {
  console.log(file, 'action, file');
  const base64 = new Promise(resolve => {
    const fileReader = new FileReader();
    fileReader.readAsDataURL(file);
    fileReader.onload = () => {
      resolve(fileReader.result);
      // console.log(fileReader.result);
      form.licenseUrl = fileReader.result
      // this.formImg = fileReader.result;
    }
  });
}
// ------------------------ 显示与隐藏 ------------------------
// 是否显示
const visibleFlag = ref(false);

function show(rowData) {

  rowData.companyProperty = rowData.companyProperty ? Number(rowData.companyProperty) : undefined
  rowData.invoiceType = rowData.invoiceType ? Number(rowData.invoiceType) : undefined
  rowData.paymentPattern = rowData.paymentPattern ? Number(rowData.paymentPattern) : undefined
  //invoiceType
  getfapTypefuun();
  getfapTypefuun2();
  getfapTypefuun3();
  // setTimeout(() => {
  Object.assign(form, formDefault);
  if (rowData && !_.isEmpty(rowData)) {
    Object.assign(form, rowData);
  }
  // }, 2000);


  visibleFlag.value = true;
  nextTick(() => {
    formRef.value.clearValidate();
  });
}

function onClose() {
  Object.assign(form, formDefault);
  visibleFlag.value = false;
}

const billType = ref([])
const billType2 = ref([])
const billType3 = ref([])
async function getfapTypefuun() {
  var res = await subcontractorInfoApi.getfapType();
  if (res.code == 0) {
    billType.value = res.data.list
  }
}
//getjiesuanType
async function getfapTypefuun2() {
  var res = await subcontractorInfoApi.getjiesuanType();
  if (res.code == 0) {
    billType2.value = res.data.list
  }
}

async function getfapTypefuun3() {
  var res = await subcontractorInfoApi.getqiyeType();
  if (res.code == 0) {
    billType3.value = res.data.list
  }
}
//getqiyeType

// ------------------------ 表单 ------------------------

// 组件ref
const formRef = ref();

const formDefault = {
  id: undefined,
  id: undefined, //id
  code: undefined, //分包商code
  companyName: undefined, //企业名称
  infoCode: undefined, //社会统一信用代码
  foundingTime: undefined, //成立时间
  legalRepresentative: undefined, //法人代表
  companyProperty: undefined, //企业性质
  businessAddress: undefined, //经营地址
  phone: undefined, //联系电话
  email: undefined, //邮箱
  contactAddress: undefined, //联系地址
  openingBank: undefined, //开户行
  receiverAccount: undefined, //收款账户
  invoiceType: undefined, //发票类别
  invoiceTaxRate: undefined, //发票税率
  paymentPattern: undefined, //结算方式
  licenseUrl: undefined, //营业执照
  remark: undefined, //备注
  createTime: undefined, //创建时间
  updateTime: undefined, //修改时间
};

let validatorPhone = (rule, value, callback) => {
  // 如果为空值，就抛出错误
  // if (!value) {
  //   callback();
  // } else {
  // 正则判断手机号格式的格式，正则判断失败抛出错误，否则直接callback()
  if (!/^1[2-9]\d{9}$/.test(value)) {
    callback(new Error("手机号格式不正确"));
  } else {
    callback();
  }
  // }
}

let validatoremail = (rule, value, callback) => {
  // 如果为空值，就抛出错误
  // if (!value) {
  //   callback();
  // } else {
  // 正则判断手机号格式的格式，正则判断失败抛出错误，否则直接callback()
  if (!/^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/.test(value)) {
    callback(new Error("邮箱格式不正确"));
  } else {
    callback();
  }
  // }
}
let validatorinfoCode = (rule, value, callback) => {
  // 如果为空值，就抛出错误
  // if (!value) {
  //   callback();
  // } else {
  // 正则判断手机号格式的格式，正则判断失败抛出错误，否则直接callback()
  if (!/[1-9A-GY]{1}[1239]{1}[1-5]{1}[0-9]{5}[0-9A-Z]{10}/.test(value)) {
    callback(new Error("社会统一信用代码格式不正确,必须18位"));
  } else {
    callback();
  }
  // }
}

let validatorlicenseUrl = (rule, value, callback) => {
  // 如果为空值，就抛出错误
  if (value) {
    callback();
  } else {
    callback(new Error("请上传营业执照"));
  }
  // }
}
///^[^_IOZSVa-z\W]{2}\d{6}[^_IOZSVa-z\W]{10}$/

let form = reactive({ ...formDefault });

const rules = {
  code: [{ required: true, message: '分包商code 必填' }],
  companyName: [{ required: true, message: '企业名称 必填' }],
  // infoCode: [{ required: true, message: '社会统一信用代码 必填' }],
  infoCode: [{ validator: validatorinfoCode, trigger: "change" }],
  foundingTime: [{ required: true, message: '成立时间 必填' }],
  legalRepresentative: [{ required: true, message: '法人代表 必填' }],
  companyProperty: [{ required: true, message: '企业性质 必填' }],
  businessAddress: [{ required: true, message: '经营地址 必填' }],
  phone: [{ validator: validatorPhone, trigger: "change" }],
  // phone: [{ required: true, message: '联系电话 必填' }],
  // email: [{ required: true, message: '邮箱 必填' }],
  email: [{ validator: validatoremail, trigger: "change" }],
  // contactAddress: [{ required: true, message: '联系地址 必填' }],
  // openingBank: [{ required: true, message: '开户行 必填' }],
  // receiverAccount: [{ required: true, message: '收款账户 必填' }],
  // invoiceType: [{ required: true, message: '发票类别 必填' }],
  // invoiceTaxRate: [{ required: true, message: '发票税率 必填' }],
  // paymentPattern: [{ required: true, message: '结算方式 必填' }],
  // contact: [{ required: true, message: '供应商联系电话 必填' }],
  licenseUrl: [{ validator: validatorlicenseUrl, trigger: "change" }],
};

// 点击确定，验证表单
async function onSubmit() {
  try {
    await formRef.value.validateFields();
    save();
  } catch (err) {
    message.error('参数验证错误，请仔细填写表单数据!');
  }
}

// 新建、编辑API
async function save() {
  SmartLoading.show();
  try {
    if (form.id) {
      await subcontractorInfoApi.update(form);
    } else {
      await subcontractorInfoApi.add(form);
    }
    message.success('操作成功');
    emits('reloadList');
    onClose();
  } catch (err) {
    smartSentry.captureError(err);
  } finally {
    SmartLoading.hide();
  }
}

defineExpose({
  show,
});
</script>
